package com.knife.oauth.config;

import com.knife.oauth.constants.KnifeOauthConstant;
import com.knife.oauth.filter.KnifeJwtAuthenticationTokenFilter;
import com.knife.oauth.util.KnifeRsaKeyUtil;
import com.nimbusds.jose.jwk.RSAKey;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

//import org.springframework.session.FindByIndexNameSessionRepository;
//import org.springframework.session.Session;
//import org.springframework.session.security.SpringSessionBackedSessionRegistry;

/**
 * 使用{@link UserDetailsService}来实现自定义的登陆认证
 *
 * @author tianhao.luo@hand-china.com
 * @version 1.0
 * @date 2021年12月02日 星期四 9:37 上午
 * @description
 * @since 1.0
 */

@Configuration
@SuppressWarnings("ALL")
public class KnifeWebSecurityConfigure extends WebSecurityConfigurerAdapter implements KnifeOauthConstant, InitializingBean {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private KnifeJwtAuthenticationTokenFilter knifeJwtAuthenticationTokenFilter;


    @Bean
    JwtEncoder jwtEncoder() throws Exception {
        RSAPrivateKey rsaPrivateKey = KnifeRsaKeyUtil.createRsaPrivateKeyByStr(rsaPrivateKeyBase64);
        RSAPublicKey rsaPublicKey = KnifeRsaKeyUtil.createRsaPublicKeyByStr(rsaPublcKeyBase64);
        RSAKey rsaKey = KnifeRsaKeyUtil.createRsaKey(rsaPublicKey, rsaPrivateKey);
        return KnifeRsaKeyUtil.createJwtEncoder(rsaKey);
    }

    @Bean
    JwtDecoder jwtDecoder() throws Exception {
        RSAPublicKey rsaPublicKey = KnifeRsaKeyUtil.createRsaPublicKeyByStr(rsaPublcKeyBase64);
        return KnifeRsaKeyUtil.createJwtDecoder(rsaPublicKey);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }

    /**
     * @return 将认证管理器暴露出去
     * @description
     * @version 1.0
     * @author tianhao.luo@hand-china.com
     * @date 2022/4/16 6:00 下午
     * @since 1.0
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 只要通过验证就可以访问所有的请求
        // authorizeRequests方法限定只对签名成功的用户请求
        // anyRequest方法限定所有请求
        // authenticated方法对所有签名成功的用户允许方法
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 登录接口，匿名访问
                // AntPathMatcher通配符规则 官方文档：https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/AntPathMatcher.html
                // The mapping matches URLs using the following rules:
                // ? matches one character
                // * matches zero or more characters
                // ** matches zero or more directories in a path
                // {spring:[a-z]+} matches the regexp [a-z]+ as a path variable named "spring"
                // 登录和注册放行
                .antMatchers(HttpMethod.POST,
                        "/v1/*/login",
                        "/v1/*/iam-user/register",
                        "/v1/*/iam-user/forget/verify-code",
                        "/v1/*/iam-user/change-password/verify-code",
                        "/v1/*/iam-user/register/*")
                .anonymous()
                .anyRequest()
                .authenticated()
                .and()
                // formLogin代表使用spring security默认的登陆页面
                //.formLogin()
                // .csrf().disable()暂时不知道如何解决跨域token问题
                // 使用jwt token，已经解决了跨域问题
                .csrf()
                .disable()
                // httpBasic方法说明启用http基础认证，会自动配置BasicAuthenticationFilter过滤器进入调用链中，并且请求头上拼接Authorization: Basic QWxhZGRpbjpvcGVuIHNLc2FtZQ==
                //.httpBasic()
        ;
        // 将自定义认证过滤器置于用户名密码过滤器之前
        http.addFilterBefore(knifeJwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        //下面的校验代码会导致循环引用，初始化失败
        //JwtEncoder jwtEncoder = jwtEncoder();
        //Assert.notNull(jwtEncoder,"jwt加密工具初始化失败");
        //JwtDecoder jwtDecoder = jwtDecoder();
        //Assert.notNull(jwtDecoder,"jwt解密工具初始化失败");

    }
}
